/* Includes ----------------------------------------------------------*/
#include "hp5804.h"

/* define ------------------------------------------------------------*/
/* typedef -----------------------------------------------------------*/
/* macro -------------------------------------------------------------*/
/* variables ---------------------------------------------------------*/
/* function prototypes -----------------------------------------------*/
extern int I2c_ExecuteCommand(void *i2c, uint8_t deviceAddr, uint8_t command);
extern int I2c_SingleWrite(void *i2c, uint8_t deviceAddr, uint8_t registerAddr, uint8_t data);
extern int I2c_MultiWrite(void *i2c, uint8_t deviceAddr, uint8_t registerAddr, uint8_t *data, uint8_t len);
extern int I2c_Read(void *i2c, uint8_t deviceAddr, uint8_t registerAddr, uint8_t *data, uint8_t len);
extern void Delay_ms(int count);
extern void Delay_us(int count);

int Hp5804_Init(struct Hp5804 *hp5804, uint32_t config)
{
    int result = 0;
    
    result = I2c_ExecuteCommand(hp5804->i2c, hp5804->devAddress, HP5804_CMD_SOFT_RST);
    Delay_ms(10);
    result = I2c_ExecuteCommand(hp5804->i2c, hp5804->devAddress, HP5804_CMD_ADC_CVT);
    result = I2c_ExecuteCommand(hp5804->i2c, hp5804->devAddress, 0x40 | (uint8_t)config);
    
    return result;
}

int Hp5804_Read(struct Hp5804 *hp5804)
{
    int32_t temperature = 0, pressure = 0;
    uint8_t array[6];
    int result = 0;
    
    result = I2c_ExecuteCommand(hp5804->i2c, hp5804->devAddress, 0x40 | HP5804_CONFIG_OSR_4096);
    Delay_ms(140);
    
    result = I2c_Read(hp5804->i2c, hp5804->devAddress, HP5804_CMD_READ_PT, array, 6);
    
    temperature |= ((uint32_t)array[0]) << 16;
    temperature |= ((uint32_t)array[1]) << 8;
    temperature |= ((uint32_t)array[2]) << 0;
    pressure |= ((uint32_t)array[3]) << 16;
    pressure |= ((uint32_t)array[4]) << 8;
    pressure |= ((uint32_t)array[5]) << 0;
    
    if((temperature & (0x00800000)) != 0)
    {   temperature |= 0xFF000000;  }
    
    if((pressure & (0x00800000)) != 0)
    {   pressure |= 0xFF000000;  }
    
    hp5804->pressure = (float)pressure * 10;
    hp5804->temperature = (float)temperature / 100;
    
    result = I2c_ExecuteCommand(hp5804->i2c, hp5804->devAddress, 0x40 | HP5804_CONFIG_OSR_4096);
    Delay_ms(140);
    result = I2c_Read(hp5804->i2c, hp5804->devAddress, HP5804_CMD_READ_P, array, 3);
    pressure = 0;
    pressure |= ((uint32_t)array[0]) << 16;
    pressure |= ((uint32_t)array[1]) << 8;
    pressure |= ((uint32_t)array[2]) << 0;
    
    return result;
}
